/**
 * 系统服务接口，如获取服务器时间等;
 * 
 */
package ms.core.serv.system;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ms.core.common.ApiResult;
import ms.core.common.RequestBody;
import ms.core.common.consts.SysErr;
import ms.core.tool.EncryptTool;
import ms.core.tool.JsonTool;
import ms.core.tool.StrTool;

public class SystemService {
	/**
	 * 接口：<div style="color:red"><b> getTime </b></div><p>
	 * 功能：获取系统时间<p>
	 * 
	 * @param p
	 * @return ApiResult对象
	 */
	public ApiResult getTime(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> body) {
		return new ApiResult(true, SysErr.CODE_SUCCESS).setData(new Date());
	}

	/**
	 * 接口：<div style="color:red"><b> shutdown </b></div><p>
	 * 功能：关闭微服务<p>
	 * 参数: signature=md5(clientId+"~"+secretKey+"-"+time)
	 * 
	 * @param p={"clientId":"客户端id","time":时间戳,"signature":"签名"}
	 * @return ApiResult对象
	 */
	public ApiResult shutdown(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> body) {
		RequestBody rb = RequestBody.getInstance(body);
		String clientId = rb.getStrValue("clientId", null);
		String signature = rb.getStrValue("signature", null);
		long time = rb.getLongValue("time", 0);
		if (StrTool.isBlank(clientId) || StrTool.isBlank(signature) || !Application.CLIENT_ID.equals(clientId) || time<0)
			return new ApiResult(false, SysErr.SYS_PARAM_ERR);

		String sign = EncryptTool.md5Encode(clientId+"~"+Application.SECRET_KEY+"-"+time);
		if (!sign.equalsIgnoreCase(signature))
			return new ApiResult(false, SysErr.SYS_SIGNATURE_ERR); 

		LWGAuthorization.stop();
		return new ApiResult(true, SysErr.CODE_SUCCESS);
	}
	
	public byte[] getBinary(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> body) {
		try {
			String txt = body!=null ? JsonTool.objectToJson(body) : "this is a testing";
			return EncryptTool.gzipString(txt);
		} catch(Exception e) {
			return null;
		}
	}
}
